package com.example.administrator.audioandvideo

import android.Manifest
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Paint
import android.media.*
import android.os.AsyncTask
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import com.example.administrator.audioandvideo.GlobalConfig.*
import java.io.*


class MainActivity : AppCompatActivity() {
    var audioRecord: AudioRecord? = null
    var isRecording: Boolean = false

    var audioTrack: AudioTrack? = null

    var fileInputStream: FileInputStream? = null

    var audioData: ByteArray? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        getPermisssion()
        var imageView = findViewById<ImageView>(R.id.image_view)
        var decodeFile = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().path + File.separator + "11.jpg")
        imageView.setImageBitmap(decodeFile)

        val surfaceView = findViewById<SurfaceView>(R.id.surface_view)
        surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) {
                var paint = Paint()
                paint.isAntiAlias = true;
                paint.style = Paint.Style.STROKE;
                var bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().name + File.separator + "11.jpg")
                var canvas = holder!!.lockCanvas()
//                canvas?.drawBitmap(bitmap, 0f, 0f, paint)
                holder.unlockCanvasAndPost(canvas)
            }

            override fun surfaceDestroyed(holder: SurfaceHolder?) {
//                TODO("not implemsented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun surfaceCreated(holder: SurfaceHolder?) {
//                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

        })
    }

    fun stopAudio(veiw: View) {
        isRecording = false
        if (null != audioRecord) {
            audioRecord!!.stop()
            audioRecord!!.release()
            audioRecord = null
        }
    }

    fun convertAudio(view:View) {
        var pcmToWavUtil = PcmToWavUtil(SAMPLE_RATE_INHZ, CHANNEL_CONFIG, AUDIO_FORMAT)
        var pcmFile = File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.pcm")
        var wavFile = File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.wav")
        if (!wavFile.mkdirs()) {
            Log.e(TAG, "wavFile Directory not created")
        }

        if (wavFile.exists()) {
            wavFile.delete()
        }

        pcmToWavUtil.pcmToWav(pcmFile.absolutePath, wavFile.absolutePath)

    }

    fun startAudio(veiw: View) {
        var minBufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE_INHZ, CHANNEL_CONFIG, AUDIO_FORMAT)
        audioRecord = AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLE_RATE_INHZ, CHANNEL_CONFIG, AUDIO_FORMAT, minBufferSize)
        var data = ByteArray(minBufferSize)


        var file = File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.pcm")
        if (!file.mkdir()) {
            Log.e(TAG, "make Directory field")
        }

        if (file.exists()) {
            file.delete()
        }

        audioRecord!!.startRecording()
        isRecording = true

        Thread(Runnable {
            var fos = FileOutputStream(file)
            while (isRecording) {
                var read = audioRecord!!.read(data, 0, minBufferSize)
                if (read != AudioRecord.ERROR_INVALID_OPERATION) {
                    fos.write(data)
                }
            }
            fos.close()
        }).start()

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    fun playAudio(view: View) {
        playInModeStream()

    }

    /**
     * 播放，使用stream模式
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    private fun playInModeStream() {
        var channelConfig = AudioFormat.CHANNEL_OUT_MONO
        var minBufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE_INHZ, channelConfig, AUDIO_FORMAT)
        var audioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()
        var audioFormat = AudioFormat.Builder().setEncoding(AUDIO_FORMAT).setChannelMask(channelConfig).setSampleRate(SAMPLE_RATE_INHZ).build()
        audioTrack = AudioTrack(audioAttributes, audioFormat, minBufferSize, AudioTrack.MODE_STREAM, AudioManager.AUDIO_SESSION_ID_GENERATE)
        audioTrack!!.play()

        var file = File(getExternalFilesDir(Environment.DIRECTORY_MUSIC), "test.pcm")
        fileInputStream = FileInputStream(file)

        Thread(Runnable {
            var buffer = ByteArray(minBufferSize)
            while (fileInputStream!!.available() > 0) {
                var readCount = fileInputStream!!.read(buffer)
                if (readCount == AudioTrack.ERROR_INVALID_OPERATION ||
                        readCount == AudioRecord.ERROR_BAD_VALUE) {
                    continue
                }
                if (readCount != 0 && readCount != -1) {
                    audioTrack!!.write(buffer, 0, minBufferSize)
                }
            }
        }).start()

    }

    fun playInModeStatic() {

       @SuppressLint("StaticFieldLeak")
       object:AsyncTask<Void,Void,Void>(){
           override fun doInBackground(vararg params: Void?): Void? {
               var openRawResource = resources.openRawResource(R.raw.ding)
               var outputStream = ByteArrayOutputStream()
               var b = 0
               b = openRawResource.read()
               while (b!=-1){
                   outputStream.write(b)
                   b = openRawResource.read()
               }
               audioData = outputStream.toByteArray()
               openRawResource.close()
               return null
           }

           override fun onPostExecute(result: Void?) {
               var audioAttributes = AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA).setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build()
               var audioFormat = AudioFormat.Builder().setSampleRate(22050).setChannelMask(AudioFormat.CHANNEL_OUT_MONO).setEncoding(AudioFormat.ENCODING_PCM_8BIT).build()
               audioTrack = AudioTrack(audioAttributes, audioFormat, audioData!!.size, AudioTrack.MODE_STATIC, AudioManager.AUDIO_SESSION_ID_GENERATE)
               audioTrack!!.write(audioData,0, audioData!!.size)
               audioTrack!!.play()
           }
       }
    }

    private val TAG = "MainActivity"

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    external fun stringFromJNI(): String

    //查看权限
    private fun getPermisssion() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                    && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "权限已经申请，可以进入了", Toast.LENGTH_SHORT).show()
            } else {
                showPermissionTip()
            }
        } else {
        }
    }

    private fun showPermissionTip() {
        //        new AlertDialog.Builder(this)
        //                .setTitle("权限通知")
        //                .setMessage("直播需要开启录音和拍照权限")
        //                .setPositiveButton("立即开启", new DialogInterface.OnClickListener() {
        //                    @Override
        //                    public void onClick(DialogInterface dialog, int which) {
        ActivityCompat.requestPermissions(this@MainActivity,
                arrayOf(Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
        //                    }
        //                }).setCancelable(false).show();
    }

    companion object {

        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")
        }
    }
}
